/**
 * 
 */
package com.imonsoft.common.util;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author LiQianHui
 * @date 2013-04-17
 * @version 2013
 */
public abstract class AjaxUtil {

	private final static Log logger = LogFactory.getLog(FileUtil.class);

	/**
	 * 直接输出纯字符串.text/plain格式
	 */
	public static void renderText(HttpServletResponse response, String text) {
		render(response, text, "text/plain;charset=UTF-8");
	}

	/**
	 * 输出JSON(JavaScript)
	 */
	public static void renderJSON(HttpServletResponse response, String text) {
		if (StringUtil.isBlank(text)) {
			text = "{}";// ...
		}
		render(response, text, "application/json;charset=UTF-8");
	}
	
	/**
	 * 输出(JSON)，仅仅在WEB容器中使用
	 * @param text
	 */
	public static void renderJSON(String text) {
		if (StringUtil.isBlank(text)) {
			text = "{}";// ...
		}
		render(ContextUtil.getHttpServletResponse(), text, "application/json;charset=UTF-8");
	}

	/**
	 * 输出JavaScript
	 */
	public static void renderJavaScript(HttpServletResponse response,
			String text) {
		render(response, text, "text/javascript;charset=UTF-8");
	}

	/**
	 * 输出HTML(text/html格式)
	 */
	public static void renderHTML(HttpServletResponse response, String text) {
		render(response, text, "text/html; charset=UTF-8");
	}

	public static void render(HttpServletResponse response, String text,
			String contentType) {
		try {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
}
